//
//  VIPMallIndex.swift
//  LeGou
//
//  Created by lxm on 2022/8/5.
//

import UIKit
import JXPagingView
import JXSegmentedView
class VIPMallIndex: ZMViewController, JXSegmentedViewDelegate {
    //MARK: --------------------属性--------------------
    let dataSource: JXSegmentedTitleDataSource = JXSegmentedTitleDataSource()
    
    var tableHeaderViewHeight: Int = Int(rpx(147))
    
    var headerInSectionHeight: Int = 58
        
    let bgView = ZMUtil.imageView(imageName: "mall_bg")
    
    var loading = XMLoadingView()
    
    var cates : [VIPMallModels.Cate]!

    //MARK: --------------------UI控件--------------------x
    let nav = NavigationBarView()
    
    lazy var pagingView: JXPagingView = preferredPagingView()
    
    let userHeaderView = ZMUtil.loadNibView(nibName: VIPMallIndexHeadView.self)
    
    lazy var vcs = preferredPagingViewVC()
    
    lazy var segmentedView: JXSegmentedView = JXSegmentedView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: CGFloat(headerInSectionHeight)))


    //MARK: --------------------生命周期--------------------
    override func viewDidLoad() {
        super.viewDidLoad()
        // bgView
        view.addSubview(bgView)
        
        hbd_barHidden = true
        view.addSubview(nav)
        nav.titleLabel.text = "创客优选"
        nav.titleLabel.font = UIFont.systemFont(ofSize: 18, weight: .medium)
        nav.backButton.isHidden = true
        nav.setMainColor(color: UIColor.zm.color333333())
        if !AppHelper.appVerify() {
            nav.setRightButton { btn in
                btn.setTitle("服务商权益", for: .normal)
                btn.setTitleColor(UIColor.zm.color333333(), for: .normal)
                btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
            } _: {
                CommonService.shared.goWeb(type: .serviceIntro)
            }
        }
        
        loading.showInView(fatherView: view)
        VIPMallService.shared.loadCategory { ok in
            if ok, let cate = VIPMallService.shared.cates {
                self.cates = cate
                self.cates.append(VIPMallModels.Cate(id: -1, name: "兑换专区"))
                self.loading.hideView(anmation: true)
                self.setUI()
                self.addConstraints()
                self.bindAction()
            } else {
                self.loading.showError("网络出错")
            }
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        ZMAppShareData.share.requestUserInfo { ok in
            
        }
    }
    //MARK: --------------------UI--------------------
    func setUI() {
        dataSource.titles = self.cates.map({$0.name})
        dataSource.isTitleColorGradientEnabled = true
        dataSource.titleNormalColor = UIColor.zm.color333333()
        dataSource.titleSelectedColor = Style.mainColor
        dataSource.titleNormalFont = UIFont.systemFont(ofSize: 17, weight: .regular)
        dataSource.titleSelectedFont = UIFont.systemFont(ofSize: 17, weight: .semibold)
        dataSource.itemSpacing = 24
        dataSource.isItemSpacingAverageEnabled = false
        
        //配置指示器
        let indicator = JXSegmentedIndicatorLineView()
        indicator.isIndicatorConvertToItemFrameEnabled = true
        indicator.indicatorColor = Style.mainColor
        indicator.indicatorWidth = 44
        indicator.verticalOffset = 10
        
        segmentedView.backgroundColor = "#F2F3F6".zm.hex()
        segmentedView.delegate = self
        segmentedView.isContentScrollViewClickTransitionAnimationEnabled = false
        segmentedView.dataSource = dataSource
        segmentedView.indicators = [indicator]
        segmentedView.backgroundColor = "#F5F5F5".zm.hex()
        segmentedView.contentEdgeInsetLeft = 12
        segmentedView.contentEdgeInsetRight = 12
//        segmentedView. = 24
        ZMUtil.clipCircle(view: segmentedView, Corner: [.topLeft, .topRight], radius: 12)
        
        segmentedView.reloadData()


        pagingView.mainTableView.gestureDelegate = self
        pagingView.mainTableView.backgroundColor = .clear
        self.view.addSubview(pagingView)
        
        segmentedView.listContainer = pagingView.listContainerView
        
        //扣边返回处理，下面的代码要加上
//        pagingView.listContainerView.scrollView.panGestureRecognizer.require(toFail: self.navigationController!.interactivePopGestureRecognizer!)
//        pagingView.mainTableView.panGestureRecognizer.require(toFail: self.navigationController!.interactivePopGestureRecognizer!)
    }
    func addConstraints() {
        nav.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
        }
        
        bgView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(rpx(255))
        }
        
        pagingView.snp.makeConstraints { make in
            make.left.bottom.right.equalToSuperview()
            make.top.equalTo(nav.snp.bottom)
        }
    }
    
    //MARK: --------------------methods--------------------
    func bindAction() {
        ZMAppShareData.share.userInfo.subscribe(onNext:{ [unowned self] resp in
            guard let resp = resp else {
                self.userHeaderView.userImg.setImage(UIImage(named: "def_user_img"), for: .normal)
                self.userHeaderView.userName.text = "未登录"
                self.userHeaderView.detailBtn.isHidden = true
                self.userHeaderView.serverIcon.isHidden = true
                self.userHeaderView.balance.text = "0"
                self.userHeaderView.frozen.text = "0"
                self.userHeaderView.integral.text = "0"
                self.userHeaderView.activity.text = "0"
                return
            }
            self.userHeaderView.userImg.zm.setImage(urlStr: resp.avatar, state: .normal, placeholder: "def_user_img")
            self.userHeaderView.userName.text = resp.phone.zm.hidPhone()
            self.userHeaderView.serverIcon.isHidden = resp.serviceProviderLevel == 0
            self.userHeaderView.detailBtn.isHidden = false
            self.mallIncomeInfo()
        }).disposed(by: disposeBag)
    }
    
    func mallIncomeInfo() {
        VIPMallAPI.mallIncomeInfo([:]).rxRequest(type:VIPMallModels.BalanceInfo.self).subscribe(onNext:{ [unowned self] resp in
            self.userHeaderView.balance.text = resp.mallMoney.zm.toString(keep: 2)
            self.userHeaderView.frozen.text = resp.mallMoneyFreeze.zm.toString(keep: 2)
            self.userHeaderView.integral.text = resp.integral.zm.toString(keep: 2)
            self.userHeaderView.activity.text = resp.totalActivity.zm.toString(keep: 2)
        }, onError: { e in
            self.loading.showError(e.localizedDescription)
        }).disposed(by: disposeBag)
    }
    
    func preferredPagingView() -> JXPagingView {
        let page = JXPagingListRefreshView.init(delegate: self)
        return page
    }
    
    func preferredPagingViewVC() -> [JXPagingViewListViewDelegate] {
        var arr = [JXPagingViewListViewDelegate]()
        for m in cates {
            if m.id == -1 {
                let vc1 = IntegralIndex()
                vc1.typeId = m.id
                vc1.openHeaderRefresh = true
                vc1.view.backgroundColor = "#F5F5F5".zm.hex()
                arr.append(vc1)
            } else {
                let vc1 = VIPMallGoodsList()
                vc1.typeId = m.id
                vc1.openHeaderRefresh = true
                vc1.view.backgroundColor = "#F5F5F5".zm.hex()
                arr.append(vc1)
            }
            
        }
        return arr
    }

    
    //MARK: --------------------delegate--------------------
}

extension VIPMallIndex : JXPagingViewDelegate {
    func pagingView(_ pagingView: JXPagingView, initListAtIndex index: Int) -> JXPagingViewListViewDelegate {
        return vcs[index]
    }
    
    func tableHeaderViewHeight(in pagingView: JXPagingView) -> Int {
        return tableHeaderViewHeight
    }

    func tableHeaderView(in pagingView: JXPagingView) -> UIView {
        return userHeaderView
    }

    func heightForPinSectionHeader(in pagingView: JXPagingView) -> Int {
        return headerInSectionHeight
    }

    func viewForPinSectionHeader(in pagingView: JXPagingView) -> UIView {
        return segmentedView
    }

    func numberOfLists(in pagingView: JXPagingView) -> Int {
        return cates.count
    }
}

extension VIPMallIndex : JXPagingMainTableViewGestureDelegate {
    func mainTableViewGestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        //禁止segmentedView左右滑动的时候，上下和左右都可以滚动
        if otherGestureRecognizer == segmentedView.collectionView.panGestureRecognizer {
            return false
        }
        return gestureRecognizer.isKind(of: UIPanGestureRecognizer.self) && otherGestureRecognizer.isKind(of: UIPanGestureRecognizer.self)
    }
}
